package controllers;

import java.io.IOException;

import java.util.Date;
import java.util.Map;


import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.*;

import org.apache.commons.io.FilenameUtils;

import models.COPSTemp;

import com.google.appengine.api.blobstore.BlobInfo;
import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

@SuppressWarnings("serial")
public class UploadfileServlet extends HttpServlet {
	private BlobstoreService blobstoreService = BlobstoreServiceFactory
			.getBlobstoreService();

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {
		BlobKey blobKey = null;
		String _key = "";
		
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		String user_email = user.getEmail().toLowerCase();
		
		
		Date today = new java.util.Date();
		// EXTRACT THE FILE FROM THE BLOB REQUEST
		@SuppressWarnings("deprecation")
		Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(req);
		String strFile_Name;
		if (blobs != null) {
			blobKey = blobs.get("txtFileName");
			if (blobKey != null) {
				final BlobInfo blobInfo = new BlobInfoFactory()
						.loadBlobInfo(blobKey);
				long size = blobInfo.getSize();
				if (size > 0) {
					// BLOB SELECTED
					strFile_Name = blobInfo.getFilename();
					strFile_Name = FilenameUtils.getName(strFile_Name);
					_key = blobKey.getKeyString();

				} else {
					// NO BLOB SELECTED - delete unnamed blob
					blobstoreService.delete(blobKey);
				}
			}
		}

		COPSTemp newitems = new COPSTemp();
		newitems.setTempPicKey(blobKey);
		newitems.setCreateDate(today);
		newitems.setCreateBy(user_email);
		
		Objectify ofy = ObjectifyService.begin();
		ofy.put(newitems);
		req.setAttribute("tempPicKey",_key);
        RequestDispatcher rd = req.getRequestDispatcher("/utils/image-crop-detail.jsp?tempPicKey="+_key);
        rd.forward(req, resp);
	}
} // Class End
